﻿using System.Web.Mvc;
using System.Text;
using System.IO;
using System.Collections.Specialized;

namespace Higgs.Web.AtomPub.ActionResults
{
    public class AtomResult : ActionResult
    {
        protected AtomResult()
        {
            Headers = new NameValueCollection();
        }

        public AtomResult(TextWriter writer, AtomType type = AtomType.Service) : this()
        {
            Writer = writer;
            Type = type;
        }

        public AtomResult(StringBuilder builder, AtomType type = AtomType.Service) : this()
        {
            Builder = builder;
            Type = type;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.RequestContext.HttpContext.Response;
            if (StatusCode.HasValue) response.StatusCode = StatusCode.Value;
            if (StatusDescription != null) response.StatusDescription = StatusDescription;

            for (var i = 0; i < Headers.Count; i++ )
            {
                response.Headers.Add(Headers.Keys[i], Headers[i]);
            }

            response.ClearContent();
            switch(Type)
            {
                case AtomType.Service:
                    response.ContentType = "application/atom+xml;type=entry";
                    break;
                case AtomType.Entry:
                    response.ContentType = "application/atomsvc+xml";
                    break;
            }

            if(Builder != null)
            {
                response.Write(Builder.ToString());
                Builder.Clear();
                Builder = null;
            }
            else
            {
                response.Write(Writer.ToString());
                Writer.Dispose();
            }

            response.Flush();
            response.End();
        }
        
        public TextWriter Writer { get; set; }
        public StringBuilder Builder { get; set; }
        public AtomType Type { get; set; }
        public int? StatusCode { get; set; }
        public string StatusDescription { get; set; }
        public NameValueCollection Headers { get; set; }
    }

    public enum AtomType
    {
        Service,
        Entry
    }
}